﻿using Eps.Ai.Common;
using InfonavaEye.components;
using InfonavaEye.handler;
using InfonavaEye.model;
using InfonavaEye.util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HeHe
{
    public class HeHeOcr
    {
        static string appId = null;
        static string secretCode = null;
        static string url = null;
        static int ocrNetworkTryCount = 0;
        //const string commonUrl = "https://api.textin.com/ai/service/v2/recognize";

        public HeHeOcr()
        {
            if (String.IsNullOrEmpty(appId))
            {
                appId = DesEncrypt.Decrypt(Config.OCR_APPID);// "4ef0abf8abf29f6a494145e26d814897";
                secretCode = DesEncrypt.Decrypt(Config.OCR_SECRET_CODE);// "6d44b915ad2067cce66ebbabfcdff500";
                url = DesEncrypt.Decrypt(Config.OCR_API_URL); // "https://api.textin.com/ai/service/v2/recognize_slices";
            }

            if (String.IsNullOrEmpty(appId) || String.IsNullOrEmpty(secretCode) || String.IsNullOrEmpty(url))
            {
                MessageBox.Show("OCR图像识别初始化参数不能为空");
            }
        }

        public void AlertTimes()
        {
            /* if (Config.OCR_USERD_TIME % 1000 == 0) {
                 MessageBox.Show($"您已使用图像识别次数为：{Config.OCR_USERD_TIME}，请注意提前充值");
             }*/
        }

        /// <summary>
        /// 图像文字识别
        /// </summary>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        public string Recognize(string imagePath, int shape)
        {
            string text = "";
            using (var client = new WebClientPro(20 * 1000))
            {
                try
                {
                    string finalUrl = null;
                    if (shape == (int)ImageShapeEnum.CIRCLE)
                    {
                        finalUrl = string.Format("{0}?check_direction={1}&recognize_option={2}", url, 1, "default");
                    }
                    else
                    {
                        finalUrl = string.Format("{0}?check_direction={1}&recognize_option={2}", url, 1, "default");//recognition_only
                    }

                    var img = GetPictureData(imagePath);
                    client.Headers.Add("x-ti-app-id", appId);
                    client.Headers.Add("x-ti-secret-code", secretCode);
                    var response = client.UploadData(finalUrl, img);

                    //记录接口调用次数
                    try
                    {
                        Config.OCR_USERD_TIMES += 1;
                        Config.INI.WriteValue("device", "OCR_USERD_TIMES", Config.OCR_USERD_TIMES.ToString());//修改配置文件
                    }
                    catch (Exception tex)
                    {
                        Console.WriteLine(tex);
                    }

                    string result = Encoding.UTF8.GetString(response);
                    JObject jo = JObject.Parse(result);
                    if (jo != null)
                    {
                        int code = jo.GetValue("code").Value<int>();
                        JToken message = jo.GetValue("message");
                        if (code == 200)
                        {
                            JToken jt = jo.GetValue("result");
                            if (jt != null)
                            {
                                JArray ja = JArray.Parse(jt["lines"].ToString());
                                if (ja.Count > 0)
                                {
                                    for (int i = 0; i < ja.Count; i++)
                                    {
                                        text = text + " " + ja[i]["text"].ToString();
                                    }
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("OCR图像识别发生异常：" + message.Value<string>());
                        }
                    }
                    Console.WriteLine(text);
                }
                catch (Exception ex)
                {
                    ocrNetworkTryCount++;
                    Console.WriteLine("对图像进行OCR识别失败，网络异常,ocrNetworkTryCount:{0} ,{1} {2},", ocrNetworkTryCount, ex.Message, ex.StackTrace);
                    if (ocrNetworkTryCount > 3&& ocrNetworkTryCount < 5) {
                        AutoCloseMessageBox.Show("网络异常，请检查网络");
                       // MessageBox.Show("网络异常，请检查网络");
                        throw new OCRNetException("OCR网络异常");
                    }
                }
            }

            if (string.IsNullOrEmpty(text))
            {
                text = "ERROR";
            }

            //将识别出的结果，如果带T就从T开始往后累加文字的顺序；
            if (text.IndexOf("T")>0) {
                var tempCodes = text.Split('T').ToList();
                var firstCode = tempCodes[0];
                tempCodes.RemoveAt(0);
                tempCodes.Insert(0,"T");
                tempCodes.Add(firstCode);
                text =String.Join(" ", tempCodes);
            }
            return text;
        }
        private static byte[] GetPictureData(string imagepath)
        {
            FileStream fs = new FileStream(imagepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            byte[] byData = new byte[fs.Length];
            fs.Read(byData, 0, byData.Length);
            fs.Close();
            return byData;
        }
    }
}
